import { useEffect, useState } from 'react';
import { FiTrash2, FiFileText } from 'react-icons/fi';
import { useTemplate } from '@/contexts/template';
import { getAssessmentTypeDisplay } from '@/types/template';
import { getAssessmentTypeColor } from '@/utils/utils';
import DeleteConfirmModal from '@/components/common/DeleteConfirmModal';
import { toast } from 'react-toastify';

export const TemplateList = () => {
  const { state, fetchTemplates, deleteTemplate } = useTemplate();
  const { templates } = state;

  const [modalOpen, setModalOpen] = useState(false);
  const [targetId, setTargetId] = useState<string | null>(null);



  useEffect(() => {
    // 首次加载模板列表
    if (templates.length === 0) fetchTemplates().catch(() => {
      toast.error('获取模板列表失败');
    });
  }, [fetchTemplates, templates.length]);

  const handleDeleteClick = (id: string) => {
    setTargetId(id);
    setModalOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (!targetId) return;
    try {
      await deleteTemplate(targetId);
      toast.success('删除成功');
    } catch (e) {
      toast.error('删除失败');
    } finally {
      setModalOpen(false);
      setTargetId(null);
    }
  };

  return (
    <div>
      {templates.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12">
          <FiFileText className="w-16 h-16 text-slate-300 mb-4" />
          <p className="text-slate-600 text-lg">暂无模板</p>
          <p className="text-slate-400 text-sm mt-1">请先上传模板文件</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {templates.map(template => (
            <div
              key={template.id}
              className="relative bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden hover:shadow-md hover:border-slate-300 transition-all duration-200 group"
            >
              {/* 删除按钮 */}
              <button
                aria-label="删除模板"
                onClick={() => handleDeleteClick(template.id)}
                className="absolute top-3 right-3 z-10 p-2 rounded-lg text-red-600 bg-white/80 backdrop-blur-sm hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-red-500 shadow-sm opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <FiTrash2 size={16} />
              </button>

              <div className="p-5">
                {/* 评估类型徽章 */}
                <div className="mb-3">
                  <span className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium border ${getAssessmentTypeColor(template.assessment_type)}`}>
                    {getAssessmentTypeDisplay(template.assessment_type)}
                  </span>
                </div>

                {/* 标题 */}
                <h3 className="text-lg font-semibold text-slate-900 mb-2 line-clamp-1 pr-8" title={template.name}>
                  {template.name}
                </h3>

                {/* 描述 */}
                <p className="text-sm text-slate-600 line-clamp-2 mb-4 min-h-[40px]" title={template.description}>
                  {template.description}
                </p>

                {/* 底部信息 */}
                <div className="flex items-center justify-between pt-3 border-t border-slate-100">
                  
                  {template.assessment_type === '105' && template.default_maturity_level && (
                    <div className="flex items-center gap-1.5">
                      <span className="text-xs text-slate-500">默认等级</span>
                      <span className="inline-flex items-center justify-center w-6 h-6 rounded-full bg-rose-100 text-rose-700 text-xs font-semibold border border-rose-200">
                        {template.default_maturity_level}
                      </span>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 删除确认弹窗 */}
      <DeleteConfirmModal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        onConfirm={handleConfirmDelete}
        itemName={templates.find(t => t.id === targetId)?.name || ''}
      />
    </div>
  );
};
